import { filter, Observable } from 'rxjs';
import { isValid, EditBox, __private } from "cc";
import { MergeWithTimer } from './Merge';

export function BindEditBox(editBox: EditBox): Observable<{ eventType: __private._cocos_ui_editbox_edit_box__EditBoxEventType, editBox: EditBox }> {
    return new Observable(observer => {
        const text_changed = editBox => {
            observer.next({ eventType: EditBox.EventType.TEXT_CHANGED, editBox });
        };
        const editing_did_ended = editBox => {
            observer.next({ eventType: EditBox.EventType.EDITING_DID_ENDED, editBox });
        };
        const editing_did_return = editBox => {
            observer.next({ eventType: EditBox.EventType.EDITING_RETURN, editBox });
        };
        editBox.node.on(EditBox.EventType.TEXT_CHANGED, text_changed)
        editBox.node.on(EditBox.EventType.EDITING_DID_ENDED, editing_did_ended);
        editBox.node.on(EditBox.EventType.EDITING_RETURN, editing_did_return);
        return () => {
            if (isValid(editBox?.node)) {
                editBox.node.off(EditBox.EventType.EDITING_DID_ENDED, editing_did_ended);
            }
        }
    });
}

// EDITING_DID_ENDED & EDITING_RETURN
export function BindEditBoxInputComplete(editBox: EditBox) {
    return MergeWithTimer([
        BindEditBox(editBox).pipe(filter(_ => [EditBox.EventType.EDITING_DID_ENDED, EditBox.EventType.EDITING_RETURN].includes(_.eventType)))
    ]);
}